import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 2.1 判断是否有token
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(function(response) {
  return response.data
},
function(error) {
  Message.error(error.response.data.msg)
  if (error.response.status === 401) {
    // 1. 跳转到登录
    router.push('/login')
    // 2. 清空用户数据
    store.commit('user/clearUserInfo')
  }
  return Promise.reject(error)
}

)

export default service
